import paho.mqtt.client as mqtt
import requests
import json

# 钉钉机器人的Webhook URL
dingding_webhook_url = "YOUR_DINGDING_WEBHOOK_URL"

mqtt_servicer = "broker.emqx.io"
mqtt_port = 1883
mqtt_keepLive = 60

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    # 订阅所有主题
    client.subscribe("#")

def on_message(client, userdata, msg):
    print(f"Received message: {msg.payload}")
    
    # 将消息转为key-value格式
    message_key_value = f"Message: {msg.payload}"

    # 发送消息到钉钉机器人
    # send_to_dingding(message_key_value)

def send_to_dingding(message):
    headers = {'Content-Type': 'application/json'}
    data = {
        "msgtype": "text",
        "text": {
            "content": message
        }
    }

    response = requests.post(dingding_webhook_url, data=json.dumps(data), headers=headers)
    if response.status_code == 200:
        print("Message sent to DingDing successfully.")
    else:
        print(f"Failed to send message to DingDing. Status Code: {response.status_code}")

# 创建MQTT客户端
client = mqtt.Client()

# 设置回调函数
client.on_connect = on_connect
client.on_message = on_message

# 连接到MQTT服务器
client.connect(mqtt_servicer, mqtt_port, mqtt_keepLive)

# 保持运行
client.loop_forever()